/**
 * project：finance-manage
 * package：com.example.dataAccess
 * 数据库 > 操作用户表
 */

package com.example.dataAccess;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.example.interfaces.UsersDAOInterface;

// import com.example.util.Constants;

// import com.example.util.Constants;

public class UsersDAO extends DAO_Base implements UsersDAOInterface {

    public UsersDAO(Connection connection) {
        super(connection);
    }

    public UsersDAO() throws IOException, SQLException {
        super();
    }

    /* 添加数据 */
    @Override
    public boolean insert(String username, String password) throws SQLException {
        String sql = "INSERT INTO users (username, password) VALUES (?,?);";
        return this.executeUpdate(sql, username, password);
    }

    /* 删除数据 */
    @Override
    public boolean delete(String username) throws SQLException {
        String sql = "DELETE FROM users WHERE username = ?;";
        return this.executeUpdate(sql, username);
    }

    /* 更新密码 */
    @Override
    public boolean update(String username, String hashPassword) throws SQLException {
        String sql = "UPDATE users SET password = ? WHERE username = ?;";
        return this.executeUpdate(sql, hashPassword, username);
    }
    
    /* 查询密码 */
    @Override
    public ResultSet selectHashPwd(String username) throws SQLException {
        String sql = "SELECT password FROM users WHERE username = ?;";
        return this.executeQuery(sql, username);
    }

    /* 建表 */
    @Override
    public boolean createTable(String tableName) throws SQLException {
        String sql = "CREATE TABLE " + tableName + " LIKE bills_default;";
        Statement statement = connection.createStatement();
        statement.executeUpdate(sql);
        statement.close();

        /* 建表失败也许会直接报错？ */
        return true;
    }
}
